package com.springbootblog.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class CurlUtils
{
    /**
     * curl post请求
     * @param urlString             请求链接（"http://example.com/api"）
     * @param jsonInputString       请求数据（JSON字符串） "{\"name\": \"John\", \"age\": 30}"
     * @return
     */
    public static String curlPost(String urlString, String jsonInputString)
    {
        String result = "";
        try
        {
            // 创建URL对象
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            // JSON请求体
            // String jsonInputString = "{\"name\": \"John\", \"age\": 30}";

            // 发送请求
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 读取响应
            int responseCode = conn.getResponseCode();
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                System.out.println("Response Code: " + responseCode);
                System.out.println("Response: " + response.toString());
                result = response.toString();
            }
            // 关闭连接
            conn.disconnect();
            return result;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * curl get请求
     * @param urlString       请求链接（"http://example.com/api?param1=" + param1 + "&param2=" + param2）
     *  // 定义请求参数
     *  String param1 = URLEncoder.encode("value1", "UTF-8");
     *  String param2 = URLEncoder.encode("value2", "UTF-8");
     *  // 构建URL
     *  String urlString = "http://example.com/api?param1=" + param1 + "&param2=" + param2;
     */
    public static String curlGet(String urlString)
    {
        String result = "";
        try {
            // String urlString = "http://example.com/api?param1=" + param1 + "&param2=" + param2;
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 设置请求方法为GET
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");

            // 读取响应
            int responseCode = conn.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK)
            {
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 打印响应
                System.out.println("Response: " + response.toString());
                result = response.toString();
            }
            else
            {
                System.out.println("GET request failed");
            }
            // 关闭连接
            conn.disconnect();
            // 返回值
            return result;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return result;
    }
}
